package com.xpgk.mvc.login;

import com.jfinal.kit.StrKit;
import com.jfinal.log.Log;
import com.xpgk.constant.ConstantRender;
import com.xpgk.constant.ConstantWebContext;
import com.xpgk.mvc.base.BaseController;
import com.xpgk.mvc.user.User;
import com.xpgk.tools.ToolWeb;

/**
 * 登陆处理
 */
public class LoginController extends BaseController {

	private static final Log log = Log.getLog(LoginController.class);

	private LoginService loginService;

	/**
	 * 准备登陆
	 */
	public void index() {
		User user = getCUser(); // cookie认证自动登陆处理
		if (null != user) {// 后台
			redirect("/index");
		} else {
			render("/login/login.html");
		}
	}

	/**
	 * 登陆验证
	 */
	public void vali() {
		// 获取表单信息
		String username = getPara("username");
		String password = getPara("password");
		String remember = getPara("remember");
		boolean authCode = authCode(); // 验证验证码
		if (authCode) {
			boolean autoLogin = false;
			if (null != remember && remember.equals("1")) { // 是否选中记住密码自动登陆
				autoLogin = true;
			}

			//复杂度
			
	      /*  if(password.length() < 6){  
	        	setAttr("msg", "密码长度最少是6位");
				setAttr("code", "400");
	        }  */
//	        if(password.matches("^[a-zA-z](.*)") && password.matches("(.*)[-`=\\\\\\[\\];',./~!@#$%^&*()_+|{}:\"<>?]+(.*)") && password.matches("(.*)\\d+(.*)")){  
	        	String result = loginService.login(getRequest(), getResponse(), username, password, autoLogin);
				if (result.equals(ConstantRender.render_success_code)) { // 登陆验证成功
					setAttr("code", ConstantRender.render_success_code);
				}else if(result.equals("5")){
					setAttr("code", "必须以字母开头,必须包含特殊字符 ,必须包含数字");
				}else if(result.equals("4")){
					setAttr("code", "密码至少是6位");
				}else{
					setAttr("msg", result);
					setAttr("code", ConstantRender.render_error_code);
				}
	        	
	      /*  }else{
	        	setAttr("msg", "必须以字母开头,必须包含特殊字符 ,必须包含数字");
				setAttr("code", "400");
	        }*/
			
		}else{
			setAttr("msg", "验证码错误");
			setAttr("code", ConstantRender.render_error_code);
		}
		renderJson();
	}
	
	/**
	 * 注销
	 */
	public void logout() {
		String cxtPath = getRequest().getContextPath();
		if(StrKit.isBlank(cxtPath)){
			cxtPath = "/";
		}
		
		ToolWeb.addCookie(getResponse(), "", cxtPath, true, ConstantWebContext.cookie_authmark, null, 0);
		redirect("/login");
	}
}
